package com.tianfeng.news.ui.dialog;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.tianfeng.news.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Data:  2019/6/21
 * Auther: xcd
 * Description:
 */
public class UpdataDialogFragment extends DialogFragment implements View.OnClickListener {

    ProgressBar progressBar;
    TextView tvOk;
    private static final String fileName = "feiniaozhuan.apk";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_fragment_updata, container);
        progressBar = view.findViewById(R.id.progress);
        tvOk = view.findViewById(R.id.ok);
        tvOk.setOnClickListener(this);
        tvOk.setVisibility(View.GONE);
        Bundle bundle = getArguments();
        if (bundle != null) {
            String url = bundle.getString("url");
            if (!TextUtils.isEmpty(url))
                downLoad(url, fileName);
        }

        getDialog().setCancelable(false);
        getDialog().setCanceledOnTouchOutside(false);
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        WindowManager.LayoutParams windowParams = window.getAttributes();
        windowParams.dimAmount = 0.5f;
        windowParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        windowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(windowParams);
        Dialog dialog = getDialog();
        if (dialog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            window.setLayout((int) (dm.widthPixels * 0.75), (int) (dm.heightPixels * 0.2));
        }
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.ok) {
            handler.sendEmptyMessage(2);
        }
    }

    public void nativeDownloadFile(String url, final File downloadFile) {
        OkHttpClient httpClient = new OkHttpClient.Builder().build();
        Request request = new Request.Builder().url(url).get().build();
        Call call = httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Log.e("TAG_文件下载", "onFailure");
//                com.vgtech.common.utils.ToastUtil.showToast("下载文件失败！！！");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                int code = response.code();
                if (code >= 500) {
                    Log.e("TAG_文件下载", "code=" + code);
//                    com.vgtech.common.utils.ToastUtil.showToast("下载文件失败！！！");
                } else if (code >= 200 && code < 300) {
                    InputStream is = response.body().byteStream();
                    byte[] buf = new byte[8 * 1024];
                    int len = 0;
                    long sum = 0;
                    long total = response.body().contentLength();
                    OutputStream fos = null;
                    try {
                        Log.e("TAG_文件下载", "downloadFile=" + downloadFile);
                        fos = new FileOutputStream(downloadFile);

                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                            sum += len;
                            int progress = (int) (sum * 1.0f / total * 100);
                            Message message = handler.obtainMessage();
                            message.what = 1;
                            message.arg1 = progress;
                            Log.e("TAG_下载完成", "progress=" + progress);
                            handler.sendMessage(message);
                        }
                        fos.flush();
                        handler.sendEmptyMessage(2);
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.e("TAG_文件下载", "IOException=");
//                        com.vgtech.common.utils.ToastUtil.showToast("下载文件失败！！！");
                    } finally {
                        if (is != null) {
                            is.close();
                        }
                        if (fos != null) {
                            fos.close();
                        }
                    }
                }

            }
        });
    }

    /**
     * 从服务器下载文件
     *
     * @param downUrl 下载文件的地址
     * @param FileName 文件名字
     */
    String savePath = null;

    public void downLoad(String downUrl, final String FileName) {
        savePath = getActivity().getExternalFilesDir(null).getAbsolutePath();
        Log.e("TAG_下载完成", "savePath=====" + savePath);
        nativeDownloadFile(downUrl, new File(savePath, FileName));
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Log.e("TAG_进度", "msg.arg1=" + msg.arg1);
                    progressBar.setProgress(msg.arg1);
                    if (msg.arg1 == 100) {
                        tvOk.setVisibility(View.VISIBLE);
                    }
                    break;
                case 2:
                    Log.e("TAG_进度", "安装");
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                    Uri data = null;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        //这里的话，我们在7.0是需要使用FileProvider;
                        data = FileProvider.getUriForFile(getActivity(),
                                "com.tianfeng.news.fileProvider", new File(savePath, fileName));
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    } else {
                        data = Uri.fromFile(new File(savePath));
                    }

                    intent.setDataAndType(data,
                            "application/vnd.android.package-archive");
                    startActivity(intent);
                    break;
            }

        }
    };
}
